import json, hashlib, struct, time
import urllib.request
from lib.settings import CHBTC_API_URL

def fill(value, lenght, fillByte):
    if len(value) >= lenght:
        return value
    else:
        fillSize = lenght - len(value)
    return value + chr(fillByte) * fillSize


def doXOr(s, value):
    slist = list(s)
    for index in range(len(slist)):
        slist[index] = chr(slist[index] ^ value)
    return "".join(slist)


def hmacSign(aValue, aKey):
    keyb = struct.pack("%ds" % len(aKey), aKey.encode('utf-8'))
    value = struct.pack("%ds" % len(aValue), aValue.encode('utf-8'))
    k_ipad = doXOr(keyb, 0x36)
    k_opad = doXOr(keyb, 0x5c)
    k_ipad = fill(k_ipad, 64, 54)
    k_opad = fill(k_opad, 64, 92)
    m = hashlib.md5()
    m.update(k_ipad.encode('utf-8'))
    m.update(value)
    dg = m.digest()

    m = hashlib.md5()
    m.update(k_opad.encode('utf-8'))
    subStr = dg[0:16]
    m.update(subStr)
    dg = m.hexdigest()
    return dg


def digest(aValue):
    value = struct.pack("%ds" % len(aValue), aValue.encode('utf-8'))
    h = hashlib.sha1()
    h.update(value)
    dg = h.hexdigest()
    return dg


def api_call(secretkey, path, params=''):
        SHA_secret = digest(secretkey)
        sign = hmacSign(params, SHA_secret)
        reqTime = (int)(time.time() * 1000)
        params += "&sign=%s&reqTime=%d" % (sign, reqTime)
        url = CHBTC_API_URL['host'] + path + '?' + params
        response = urllib.request.urlopen(url, timeout=5)
        doc = json.loads(response.read().decode('utf-8'))
        return doc

def sort_and_format(l, reverse=False):
    l.sort(key=lambda x: float(x[0]), reverse=reverse)
    r = []
    for i in l:
        r.append({'price': float(i[0]), 'volume': float(i[1])})
    return r